import requests
import uuid
import os

from CloudEngine.IO.IVTKReader import IVTKReader
from CloudEngine.core.VTActor import VTActor
from CloudEngine.utils.file import write_file


def read_vtk(service, options):
    reader_instance = IVTKReader(options.get("DataType"))
    url = options.get("url")
    current_dir = os.getcwd()
    if url and url.startswith("http"):
        content = requests.get(url).content
        path = current_dir + "/temp/" + uuid.uuid4() + ".vtk"
        write_file(path, content)
    else:
        path = url
    reader_instance.read(path)
    if options.get("DataType") == "dataset":
        poly_data = reader_instance.output()
        op = {}
        if options.get("ParseAttributes"):
            op["parse_attributes"] = options.get("ParseAttributes")
        if options.get("ColorType"):
            op["ColorType"] = options.get("ColorType", "")
            op["ColorLevels"] = options.get("ColorLevels", 256)
        if options.get("IsVector", None) is not None:
            op["IsVector"] = options.get("IsVector")
        actor = VTActor(poly_data, op)
        service.model_add(actor)
        if actor.vector_actor is not None:
            service.model_add(actor.vector_actor)
        return actor.id

    return None
